import {AMapKey} from '@/constant'
import AMapLoader from '@amap/amap-jsapi-loader'



export default {
  methods: {
    initMap() {
      return new Promise(resolve => {
        if(window.AMap && !this.AMap) {
          AMapLoader.reset()
        }

        if(this.AMap) {
          resolve()
        }
        AMapLoader.load({
          key: AMapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
          plugins: ['AMapKey', 'AMap.Geocoder'] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
          this.AMap = AMap
          resolve(AMap)
        }).catch(e => {
          console.error(e);


        })
      })
    },
    geocoder() {
      if(!this.geocoderInstance) {
        this.geocoderInstance = new this.AMap.Geocoder({
          city: '成都', // 城市设置，默认：“全国”
          batch: true
        })
      }
      return this.geocoderInstance
    },
    getLocation(geocoder, address) {
      if(!geocoder) {
        geocoder = this.geocoder()
      }
      return new Promise(resolve => {
        geocoder.getLocation(address, (status, result) => {
          if(status === 'complete' && result.geocodes.length) {
            resolve(result.geocodes)
          } else {
            console.error('坐标获取失败:', result)
            resolve(result.geocodes)
          }
        })
      })
    }
  }
}
